package com.jcf.springboot.security.util;

import com.jcf.springboot.common.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "markerhub.jwt")
public class JwtUtil {

  private long expire;
  private String secret;
  private String header;

  // 生成jwt
  public String generateToken(String username) {

    Date nowDate = new Date();
    Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
    log.info("过期时间" + expireDate);
    return Jwts.builder()
     .setHeaderParam("typ", "JWT")
     .setSubject(username)
     .setIssuedAt(nowDate)
     .setExpiration(expireDate)
     .signWith(SignatureAlgorithm.HS512, secret)
     .compact();
  }

  // 解析jwt
  public Claims getClaimByToken(String jwt) {
    return Jwts.parser()
     .setSigningKey(secret)
     .parseClaimsJws(jwt)
     .getBody();
  }

  // jwt是否过期
  public boolean isTokenExpired(Claims claims) {
    return claims.getExpiration().before(new Date());
  }


  public R validateJWT(String jwtStr) {
    Claims claims = null;
    R r = null;
    try
    {
      claims = getClaimByToken(jwtStr);
      r = R.ok().data("claims", claims);
    }
    catch (ExpiredJwtException e)
    {
      r = R.error().code(JwtConstant.JWT_ERRCODE_EXPIRE).data("claims",null);
    }
    catch (SignatureException e)
    {
      r = R.error().code(JwtConstant.JWT_ERRCODE_FAIL).data("claims",null);;

    }
    catch (Exception e)
    {
      r =R.error().code(JwtConstant.JWT_ERRCODE_FAIL).data("claims",null);;

    }
      return r;
  }

}
